<?php
namespace app\admin\model;

use think\Model;

/**
 * 系统配置模型
 */
class SystemConfig extends Model
{
    protected $name = 'system_config';
    protected $autoWriteTimestamp = true;
    protected $createTime = 'created_at';
    protected $updateTime = 'updated_at';
    
    /**
     * 获取配置值
     * @param string $key 配置键
     * @param mixed $default 默认值
     * @return mixed
     */
    public static function getValue($key, $default = null)
    {
        $config = self::where('config_key', $key)->find();
        return $config ? $config->config_value : $default;
    }
    
    /**
     * 设置配置值
     * @param string $key 配置键
     * @param mixed $value 配置值
     * @param string $group 配置分组
     * @param string $description 配置描述
     * @return bool
     */
    public static function setValue($key, $value, $group = 'system', $description = '')
    {
        $config = self::where('config_key', $key)->find();
        
        if ($config) {
            // 更新
            $config->config_value = $value;
            $config->config_group = $group;
            if ($description) {
                $config->description = $description;
            }
            return $config->save();
        } else {
            // 新增
            $config = new self();
            $config->config_key = $key;
            $config->config_value = $value;
            $config->config_group = $group;
            $config->description = $description;
            return $config->save();
        }
    }
    
    /**
     * 批量设置配置
     * @param array $data 配置数据
     * @param string $group 配置分组
     * @return bool
     */
    public static function setValues($data, $group = 'system')
    {
        try {
            foreach ($data as $key => $value) {
                self::setValue($key, $value, $group);
            }
            return true;
        } catch (\Exception $e) {
            return false;
        }
    }
    
    /**
     * 获取分组配置
     * @param string $group 配置分组
     * @return array
     */
    public static function getGroupConfig($group = 'system')
    {
        $configs = self::where('config_group', $group)->select();
        $result = [];
        foreach ($configs as $config) {
            $result[$config->config_key] = $config->config_value;
        }
        return $result;
    }
    
    /**
     * 删除配置
     * @param string $key 配置键
     * @return bool
     */
    public static function deleteConfig($key)
    {
        return self::where('config_key', $key)->delete() > 0;
    }
}

